import router from '../router'
//import Qs from 'qs'
const axios = require('axios');


export default async(type = 'GET', url = '', data = {}, method = 'fetch') => {

	type = type.toUpperCase();

	//把空属性去掉。
	Object.keys(data).forEach(key => {
		if(data[key] === undefined || data[key] === ''){
			delete data[key];
		}
	})

	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {

		let requestConfig = {
			credentials: 'include',
			method: type,
			headers: {
				'Accept': 'application/json',
				'Content-Type' : 'application/json',
				//'content-type': 'application/x-www-form-urlencoded',
			},
			mode: "cors",
			cache: "no-cache",
		}

		if (type == 'POST') {
			Object.defineProperty(requestConfig, 'body', {
				value: JSON.stringify(data)
			})
		}
		
		var responseJson = {};

		try {
			var response = await fetch(url, requestConfig);
			responseJson = await response.json();

			if(responseJson.errcode && responseJson.errcode != 0){
				console.log(url);
				console.log(responseJson.errmsg);

				//未登录,自动跳转登录页
				if(responseJson.errcode == 1001){
					router.push({ 
						name: 'login', 
					});
				}
			}
		} catch (error) {
			console.log(error);
			//throw new Error(error)
		}
		return responseJson;
	} else {

		const config = {
			'method' : type,
			'url' : url,
			'data' : data,
			'headers' : {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
			},
		};

		var response = {};
		try {
		    response = await axios(config);
		} catch (error) {
			console.log('axios 中的异常 ： ' + error);
			console.log(error);
		}

		return response.data;

		// let requestObj;
		// if (window.XMLHttpRequest) {
		// 	requestObj = new XMLHttpRequest();
		// } else {
		// 	requestObj = new ActiveXObject;
		// }

		// let sendData = '';
		// if (type == 'POST') {
		// 	if(data['php']){
		// 		delete data['php'];
		// 		sendData = Qs.stringify(data);
		// 	}else{
		// 		sendData = JSON.stringify(data);
		// 	}
			
		// }

		// requestObj.open(type, url, true);
		// requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		// requestObj.send(sendData);

		// requestObj.onreadystatechange = () => {
		// 	if (requestObj.readyState == 4) {
		// 		if (requestObj.status == 200) {
		// 			let obj = requestObj.response
		// 			if (typeof obj !== 'object') {
		// 				obj = JSON.parse(obj);
		// 			}
		// 			if(obj.errcode && obj.errcode != 0){
		// 				console.log(url);
		// 				console.log(obj.errmsg);

		// 				//未登录,自动跳转登录页
		// 				if(obj.errcode == 1001){
		// 					router.push({ 
		// 						name: 'login', 
		// 					});
		// 				}
		// 			}
		// 			return obj
		// 		} else {
		// 			throw new Error(requestObj)
		// 		}
		// 	}
		// }
	}
}